package com.jgp.config;

import com.jgp.common.utils.JGPUtil;
import com.jgp.mico.client.MicroClient;
import com.jgp.mico.client.MicroClientFormHttpMessageConverter;
import com.jgp.sys.props.MicroConfigPropBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.cloud.client.loadbalancer.LoadBalanced;
import org.springframework.cloud.netflix.eureka.EnableEurekaClient;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.annotation.Order;
import org.springframework.http.MediaType;
import org.springframework.http.converter.ByteArrayHttpMessageConverter;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.ResourceHttpMessageConverter;
import org.springframework.http.converter.StringHttpMessageConverter;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
import org.springframework.http.converter.xml.SourceHttpMessageConverter;

import java.nio.charset.Charset;
import java.util.Arrays;
import java.util.List;

/**
 * 项目   jgp-micro-provider
 * 作者   loufei
 * 时间   2018/11/29
 */
@Order(400)
@Configuration
@EnableEurekaClient
@ConditionalOnProperty(prefix = "jgp.micro", name = "enabled", havingValue = "true")
@EnableConfigurationProperties({MicroConfigPropBean.class})
public class MicroClientConfiguration {
    
    public static List<HttpMessageConverter<?>> CONVERTERS;

    static {
        HttpMessageConverter<?> converter1 = new ByteArrayHttpMessageConverter();
        HttpMessageConverter<?> converter2 = new StringHttpMessageConverter(Charset.forName("utf-8"));
        HttpMessageConverter<?> converter3 = new ResourceHttpMessageConverter();
        HttpMessageConverter<?> converter4 = new SourceHttpMessageConverter();
        HttpMessageConverter<?> converter5 = new MicroClientFormHttpMessageConverter();
        MappingJackson2HttpMessageConverter converter6 = new MappingJackson2HttpMessageConverter();
        converter6.setSupportedMediaTypes(Arrays.asList(MediaType.APPLICATION_JSON_UTF8, MediaType.TEXT_PLAIN));
        converter6.setObjectMapper(JGPUtil.MAPPER);
        CONVERTERS = Arrays.asList(converter1, converter2, converter3, converter4, converter5,converter6);
    }
    
    @Value("${spring.profiles.active}")
    private String profile;
    
    @Autowired
    private MicroConfigPropBean microConfigPropBean;
    
    @Bean
    @LoadBalanced
    public MicroClient microClient() {
        MicroClient microClient = new MicroClient(profile,microConfigPropBean);
        microClient.setMessageConverters(CONVERTERS);
        return microClient;
    }
    
}
